import React, {Component} from 'react';
import { Menu, Spin} from 'antd';
import PropTypes from 'prop-types';
import {initPanels} from "../../../state/action/comAction";
import fetchHandler from '../../../fetch/fetchHandler';
import {getUserMenuList} from '../../../fetch/fetchApi';
const SubMenu = Menu.SubMenu;

/*
*  数据菜单组件
*  @class StarMenu
*  @property openMenuArr {Array} 已展开的菜单数组
*  @property rootSubmenuKeys {Array} 父菜单的key值数组
*  @state menuList {Object} 用户构建菜单渲染的数据对象
*  @state defaultSelectedkeys 默认选择的菜单key
* */

class StarMenu extends Component {

  static contextTypes = {
    router: PropTypes.object.isRequired,
    store: PropTypes.object.isRequired
  }

  constructor (props) {
    super();
    this.props = props;
    this.rootSubmenuKeys = [];
    this.openMenuArr = [];
    this.state = {
      menuList: null,
      defaultselectedkeys: []
    };
  }

  componentWillMount () {
    this.getUserMenuList();
  }

  // 获取菜单列表数据

  getUserMenuList () {

    // 通过fetchHandler公共函数来处理接口数据，成功请求则返回包含数据和对应code的对象，否则通过message进行提示。

    fetchHandler(getUserMenuList).then((res) => {
      if (res) {
        // res.data === null ? 已登录，没有菜单信息，返回无菜单提示页 : 已登录且有菜单信息
        res.data ?
        (
          this.setState({'menuList': res.data}),
            this.getDefaultPage(res.data[0])
        ): res.code === 'fail' ? this.context.router.history.push('login') :
          this.context.router.history.push('nomenu');
      } else {
        // token过期，清除token返回登录
        window.sessionStorage.removeItem('token');
        this.context.router.history.push('login');
      }
    });
  }

  // 返回默认首页

  getDefaultPage (page) {
    if (page) {
      if (page.childList) {
        const p = page.childList[0];
        this.openMenuArr.push(page.id);
        this.getDefaultPage(p);
      } else {
        // 设置默认初始tab
        const tab = [{ title: page.title, content: this.props.Frame[page.id], key: page.id, closable: false }];
        const pageId = page.id;
        this.setState({
          selectedkeys: [page.id],
          defaultopenkeys: this.openMenuArr,
          openkeys: this.openMenuArr
        });
        // 更新Panels数组状态
        this.context.store.dispatch(initPanels(tab, pageId));
      }
    }
  }

  // 根据数据构建菜单

  generateMenu (menuArr) {
  let menuDom = [];
  if (menuArr) {
    for (let m of menuArr) {
      if (m.childList === null) {
        menuDom.push(<Menu.Item key={m.id} uri={m.uri}>
          <span uri={m.uri}>{m.title}</span>
        </Menu.Item>);
      } else {
        this.rootSubmenuKeys.push(m.id);
        menuDom.push(
          <SubMenu key={m.id} title={<span><span>{m.title}</span></span>}>
            {this.generateMenu(m.childList)}
          </SubMenu>
        );
      }
    }
    return menuDom;
  }
  }

  // 打开子菜单关闭父菜单及兄弟菜单
  onOpenChange (openKeys) {
    const latestOpenKey = openKeys.find(key => this.state.openkeys.indexOf(key) === -1);
    const latestLen = latestOpenKey ? latestOpenKey.length : 0;
    let latestOpenKeyArr = [];
    for (let i = 0; i < latestLen; i += 2) {
      latestOpenKeyArr.push(latestOpenKey.substr(0, latestLen - i));
    }
    if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      this.setState({ openkeys: openKeys });
    } else {
      this.setState({
        openkeys: latestOpenKey ? latestOpenKeyArr : [],
      });
    }
  }

  render() {
    return (
      <div>
        {
          this.state.defaultopenkeys
          && this.state.defaultopenkeys[0]
          && <Menu className={'ant-scroll-menu'} theme="dark" mode="inline"
                 defaultSelectedKeys={this.state.selectedkeys}
                 openKeys={this.state.openkeys}
                 onOpenChange={this.onOpenChange.bind(this)}
                 onClick={this.props.addTab}>
          {
            this.generateMenu(this.state.menuList)
          }
        </Menu>
        }
        {!this.state.menuList && <Spin />}
      </div>
    );
  }
}

export default StarMenu;

StarMenu.propsType = {
  addTab: PropTypes.func.isRequired,
  Frame: PropTypes.object.isRequired
}